package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import main.DataTransferObject;
import main.MyConnection;

public class AlgorithmDAOImpl implements AlgorithmDAO {

	@Override
	public boolean createOrUpdate(DataTransferObject inDTO) {
		return createOrUpdate(inDTO.getAlgorithmName());
	}

	@Override
	public boolean createOrUpdate(String algorithmName) {
		try{
			Connection conn = MyConnection.getConnection();
			String sql = "SELECT * FROM Algorithm WHERE Alg_Name = ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, algorithmName);
			ps.execute();
	
			ResultSet rs = ps.getResultSet();
			if(rs.next()){ 
				//Do nothing since all that needs to update is the Algorithm
			} 
			else {
				sql = "INSERT INTO Algorithm (Alg_Name) VALUES (?)";
				ps = conn.prepareStatement(sql);
				ps.setString(1, algorithmName);
				ps.execute();
			}
		} catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public DataTransferObject getAlgorithmFromName(String algorithmName) {
		DataTransferObject dto = null;
		try{
			Connection conn = MyConnection.getConnection();
			String sql = "SELECT * FROM Algorithm WHERE Alg_Name = ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, algorithmName);
			ps.execute();
	
			ResultSet rs = ps.getResultSet();
			if(rs.next()){ 
				dto = new DataTransferObject();
				dto.setAlgID(rs.getInt("Alg_ID"));
				dto.setAlgorithmName(rs.getString("Alg_Name"));
			} 

		} catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return dto;
	}
}
